package com.hnkywl.sts.service.cggl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.dao.cggl.CgdDao;
import com.hnkywl.sts.dao.cggl.CgdmxDao;
import com.hnkywl.sts.dao.cggl.GlfyDao;
import com.hnkywl.sts.dao.cggl.GlfymxDao;
import com.hnkywl.sts.dao.htgl.CghtDao;
import com.hnkywl.sts.dao.htgl.XshtDao;
import com.hnkywl.sts.dao.jhgl.BgjhDao;
import com.hnkywl.sts.dao.jhgl.BgjhmxDao;
import com.hnkywl.sts.dao.jsgl.CgjsdDao;
import com.hnkywl.sts.dao.jsgl.CgjsdmxDao;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.dao.sys.GgDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.dao.xsgl.ShjDao;
import com.hnkywl.sts.dao.xsgl.XsdDao;
import com.hnkywl.sts.dao.xsgl.XsmxDao;
import com.hnkywl.sts.dao.zjgl.BzjDao;
import com.hnkywl.sts.entity.base.Sjzdz;
import com.hnkywl.sts.entity.cggl.*;
import com.hnkywl.sts.entity.htgl.Cght;
import com.hnkywl.sts.entity.htgl.Htmx;
import com.hnkywl.sts.entity.htgl.Xsht;
import com.hnkywl.sts.entity.jhgl.Bgjh;
import com.hnkywl.sts.entity.jhgl.Bgjhhzmx;
import com.hnkywl.sts.entity.jhgl.Bgjhmx;
import com.hnkywl.sts.entity.jhgl.Tpwzjh;
import com.hnkywl.sts.entity.sys.Gg;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.entity.xsgl.Xsd;
import com.hnkywl.sts.entity.xsgl.Xsmx;
import com.hnkywl.sts.service.base.BmService;
import com.hnkywl.sts.service.base.SjzdzService;
import com.hnkywl.sts.service.base.WebserviceTransService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.service.xsgl.KhService;
import com.hnkywl.sts.service.xsgl.XsdService;
import com.hnkywl.sts.service.zjgl.BzjService;
import com.hnkywl.sts.util.CalcUtils;
import com.hnkywl.sts.util.ReflectionUtils;
import net.ruixin.orm.hibernate.Page;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-4-23
 * Time: 上午11:10
 * To change this template use File | Settings | File Templates.
 */
@Service
public class CgdService {
    private CgdDao cgdDao;
    private CgdmxDao cgdmxDao;
    private KhService khService;
    private KhDao khDao;
    private XsdDao xsdDao;
    private CghtDao cghtDao;
    private XshtDao xshtDao;
    private XsdService xsdService;
    private GlfymxDao glfymxDao;
    private BmService bmService;
    private GlfyDao glfyDao;
    private SjzdzService sjzdzService;
  //  private YgService ygService;
    private XsmxDao xsmxDao;
    private CgjsdDao cgjsdDao;
    private CgjsdmxDao cgjsdmxDao;
    private BgjhmxDao bgjhmxDao;
    private BgjhDao bgjhDao;
    private GgDao ggDao;
    private ShjDao shjDao;
//    private GsjgDao gsjgDao;
//    private BzjDao bzjDao;

    private WebserviceTransService webserviceTransService;
//    private BzjService bzjService;


    public String findAllCgdList(String wzbm, String cgdh, String htbm, Long dzckId, Date fhrqStart, Date fhrqEnd, String cglx, Long cggsId, Long cgbmId, Long cgrId, String zt, String sftzd, String htType, Long gysid, String rkzt, String zdr, Boolean dlkhcgd, int page, int rows) throws ParseException {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page cgdPage = this.cgdDao.findAllCgdList(null, wzbm, cgdh, htbm, dzckId, fhrqStart, fhrqEnd, cglx, cggsId, cgbmId, cgrId, zt, sftzd, htType, gysid, rkzt, zdr, dlkhcgd, page, rows);
        List<Map> sumList = cgdDao.findSumCgd(null, wzbm, cgdh, dzckId, fhrqStart, fhrqEnd, cglx, cggsId, cgbmId, cgrId, zt, sftzd, htType, gysid, rkzt, zdr, dlkhcgd);
        String cgdmxJson = gson.toJson(cgdPage.getResult());
        Double cgsl = 0d;
        Double hse = 0d;
        Double gylfyje = 0d;
        if (sumList.size() != 0) {
            for (Map map : sumList) {
                cgsl += Double.valueOf((map.get("cgsl") == null ? 0d : map.get("cgsl")).toString());
                hse += Double.valueOf((map.get("cgje") == null ? 0d : map.get("cgje")).toString());
                gylfyje += Double.valueOf((map.get("gylfyje") == null ? 0d : map.get("gylfyje")).toString());
            }
            return "{\"total\":" + cgdPage.getTotalCount() + ",\"rows\":" + cgdmxJson + ",\"footer\":[{\"cgdh\":\"合计:\",\"cgsl\":" + cgsl + ",\"cgje\":" + hse + ",\"glfyje\":" + gylfyje + "}]}";
        } else {
            return "{\"total\":" + cgdPage.getTotalCount() + ",\"rows\":" + cgdmxJson + "}";
        }
    }


    public String findAllCgdtzList(String wzbm, String cgdh, Long dzckId, Date fhrqStart, Date fhrqEnd, String cglx, Long cggsId, Long cgbmId, Long cgrId, String zt, String sftzd, String htType, Long gysid, String rkzt, int page, int rows) throws ParseException {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page cgdPage = this.cgdDao.findAllCgdtzList(null, wzbm, cgdh, dzckId, fhrqStart, fhrqEnd, cglx, cggsId, cgbmId, cgrId, zt, sftzd, htType, gysid, rkzt, page, rows);
//        List<Map> sumList = cgdDao.findSumCgd(null, wzbm, cgdh, dzckId, fhrqStart, fhrqEnd, cglx, cggsId, cgbmId, cgrId, zt, sftzd, htType, gysid, rkzt);
        String cgdmxJson = gson.toJson(cgdPage.getResult());
//        Double cgsl = 0d;
//        Double hse = 0d;
//        Double gylfyje = 0d;
//        if (sumList.size() != 0) {
//            for (Map map : sumList) {
//                cgsl += Double.valueOf((map.get("cgsl") == null ? 0d : map.get("cgsl")).toString());
//                hse += Double.valueOf((map.get("cgje") == null ? 0d : map.get("cgje")).toString());
//                gylfyje += Double.valueOf((map.get("gylfyje") == null ? 0d : map.get("gylfyje")).toString());
//            }
//            return "{\"total\":" + cgdPage.getTotalCount() + ",\"rows\":" + cgdmxJson + ",\"footer\":[{\"cgdh\":\"合计:\",\"cgsl\":" + cgsl + ",\"cgje\":" + hse + ",\"glfyje\":" + gylfyje + "}]}";
//        } else {
        return "{\"total\":" + cgdPage.getTotalCount() + ",\"rows\":" + cgdmxJson + "}";
//        }
    }

    public Page<Cgd> findCgjlQuery(Long cghtId, int pageNo, int pageSize) {
        return this.cgdDao.findCgjlQuery(cghtId, pageNo, pageSize);
    }

    public Page<Map> findByYtjQuery(Long dhck, String yrk, String sfys, String lx, Long cggsId, Long cgbmId, Long cgrId, String cgdh, String wzbm, Long gysid, Date fhrqStart, Date fhrqEnd, Integer sfgq, int pageNo, int pageSize) {
        return this.cgdDao.findByYtjQuery(dhck, yrk, sfys, lx, cggsId, cgbmId, cgrId, cgdh, wzbm, gysid, fhrqStart, fhrqEnd, sfgq, pageNo, pageSize);
    }

    /**
     * 首页采购单数
     *
     * @return
     */
    public String findAllCgd() {
        return this.cgdDao.findAllCgd();
    }


    /**
     * 通过采购单号查找采购单
     *
     * @param cgdh
     * @return
     */
    public Cgd findByCgdh(String cgdh) {
        return this.cgdDao.findUniqueByProperty("cgdh", cgdh);
    }

    /**
     * 首页入库验收单数
     *
     * @return
     */
    public String findAllCgdRkys(String sfys, String yrk) {
        BigDecimal cgdNum = new BigDecimal(0);
        try {
            cgdNum = this.cgdDao.findCgdList(sfys, yrk);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cgdNum.toString();
    }

    public Cgd findCgdDetail(Long cgdId) {
        return this.cgdDao.get(cgdId);
    }

    public Cgd findCgdByXsd(Long xsdId) {
        return this.cgdDao.findUniqueByProperty("xsd.id", xsdId);
    }

    @Transactional
    public void editCgdtz(Cgd cgd, List<Cgdmx> mxlist, Cgd hccgd, Cgd ycgd) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, SQLException {
        cgd.setId(null);
        cgd.setYjs(false);
        cgd.setCgjsd(null);
        cgd.setFjList(null);
        hccgd.setId(null);
        hccgd.setYjs(false);
        hccgd.setCgjsd(null);
        hccgd.setFjList(null);

        List<Cgdmx> cgdmxList = ycgd.getCgdmxList();
        List<Glfy> cgfyList = ycgd.getCgfyList();

        List<Cgdmx> hccgdmxList = new ArrayList<Cgdmx>();
        List<Glfy> hcglfyList = new ArrayList<Glfy>();

        for (Cgdmx cgdmx : cgdmxList) {
            Cgdmx hccgdmx = new Cgdmx();
            PropertyUtils.copyProperties(hccgdmx, cgdmx);
            hccgdmx.setId(null);
            hccgdmx.setYjs(false);
            hccgdmx.setCgjsd(null);
            hccgdmx.setMxh(cgdmx.getMxh());
            if (cgdmx.getSbsl() != null)
                hccgdmx.setSbsl(0 - cgdmx.getSbsl());
            if (cgdmx.getRkjs() != null)
                hccgdmx.setRkjs(0 - cgdmx.getRkjs());
            hccgdmx.setRksl(0 - cgdmx.getRksl());
            hccgdmx.setCreateUser(YgService.getCurrentYg());
            hccgdmx.setCreateOrgan(cgd.getSbgs());
            hccgdmx.setCreateDepartment(cgd.getSbbm());
            hccgdmx.setDateCreated(new Date());
            hccgdmx.setLastUpdated(hccgdmx.getDateCreated());
            if (cgdmx.getBgjhhzmxList() != null) {
                List<Bgjhhzmx> list = new ArrayList<Bgjhhzmx>();
                for (Bgjhhzmx bgjhhzmx : cgdmx.getBgjhhzmxList()) {
                    list.add(bgjhhzmx);

                    if (this.cgdDao.calcCgdmxSbsl(bgjhhzmx.getId(), hccgdmx) >= bgjhhzmx.getJhsl())
                        bgjhhzmx.setZt(8);
                    else
                        bgjhhzmx.setZt(7);
                }
                hccgdmx.setBgjhhzmxList(list);
            }
            hccgdmxList.add(hccgdmx);
            if (cgdmx.getKh() != null) {
                khDao.updateKhSl(cgdmx.getKh().getId(), cgdmx.getRksl());
            }
        }
        for (Glfy cgfy : cgfyList) {
            Glfy hccgfy = new Glfy();
            PropertyUtils.copyProperties(hccgfy, cgfy);
            hccgfy.setId(null);
            hccgfy.setJfsl(0 - cgfy.getJfsl());
            hccgfy.setJe(0 - cgfy.getJe());
            hccgfy.setCreateUser(YgService.getCurrentYg());
            hccgfy.setCreateOrgan(cgd.getSbgs());
            hccgfy.setCreateDepartment(cgd.getSbbm());
            hccgfy.setDateCreated(new Date());
            hccgfy.setLastUpdated(hccgfy.getDateCreated());
            if (cgfy.getGlfymxList() != null) {
                List<Glfymx> gylfymxList = new ArrayList<Glfymx>();
                for (Glfymx glfymx : hccgfy.getGlfymxList()) {
                    Glfymx hcglfymx = new Glfymx();
                    PropertyUtils.copyProperties(hcglfymx, glfymx);
                    hcglfymx.setId(null);
                    hcglfymx.setJtfy(0 - glfymx.getJtfy());
                    hcglfymx.setJsjtfy(0 - glfymx.getJsjtfy());
                    hcglfymx.setGlfy(hccgfy);
                    this.glfymxDao.save(hcglfymx);
                    gylfymxList.add(hcglfymx);
                }
                hccgfy.setGlfymxList(gylfymxList);
            }
            hcglfyList.add(hccgfy);
        }

        //保存原采购单
        ycgd.setSftzd(true);
        ycgd.setYcgd(ycgd);
        ycgd.setLastUpdated(new Date());
        if (ycgd.getCglx().equals("zddh") && !"保兑仓".equals(ycgd.getCght().getRzlx().getMc())) {
            ycgd.getXsd().setSftzd(true);
            Xsd yxsd = this.xsdDao.get(ycgd.getXsd().getId());
            Xsd hcxsd = operateHcXsd(yxsd);
            hccgd.setXsd(hcxsd);
        }

        //保存红冲的采购单
        hccgd.setCgdh(this.bmService.getCgdbm(hccgd.getCglx()));
        hccgd.setSftzd(true);
        hccgd.setCgdmxList(hccgdmxList);
        hccgd.setCgfyList(hcglfyList);
        hccgd.setYsrq(new Date());
        hccgd.setRksj(new Date());
        hccgd.setCreateUser(YgService.getCurrentYg());
        hccgd.setCreateOrgan(cgd.getSbgs());
        hccgd.setCreateDepartment(cgd.getSbbm());
        hccgd.setDateCreated(new Date());
        hccgd.setLastUpdated(hccgd.getDateCreated());

        hccgd.setYcgd(ycgd);

        if (ycgd.getYsgjList() != null && ycgd.getYsgjList().size() == 0) {
            ycgd.setYsgjList(null);
        }
        if (hccgd.getYsgjList() != null && hccgd.getYsgjList().size() == 0) {
            hccgd.setYsgjList(null);
        }
        this.cgdDao.save(ycgd);
        this.cgdDao.save(hccgd);

        //保存新采购单
        cgd.setCgdh(this.bmService.getCgdbm(cgd.getCglx()));
        cgd.setYcgd(ycgd);
        cgd.setZt("ytj");
        cgd.setYrk(false);
        cgd.setYjs(false);
        cgd.setCreateUser(YgService.getCurrentYg());
        cgd.setCreateOrgan(cgd.getSbgs());
        cgd.setCreateDepartment(cgd.getSbbm());
        cgd.setDateCreated(new Date());
        cgd.setLastUpdated(cgd.getDateCreated());

        if (cgd.getCgfyList() != null && cgd.getCgfyList().size() == 0) {
            cgd.setCgfyList(null);
        } else if (cgd.getCgfyList() != null && cgd.getCgfyList().size() > 0) {
            List<Glfy> glfyList = new ArrayList<Glfy>();
            for (Glfy glfy : cgd.getCgfyList()) {
                Glfy xglfy = new Glfy();
                PropertyUtils.copyProperties(xglfy, glfy);
                xglfy.setId(null);
                glfyList.add(xglfy);
            }
            cgd.setCgfyList(glfyList);
        }

        for (int i = 0; i < mxlist.size(); i++) {
            Cgdmx cgdmx = mxlist.get(i);
            for (Cgdmx ycgdmx : cgdmxList) {
                if (cgdmx.getGg().getId().equals(ycgdmx.getGg().getId())) {
                    List<Bgjhhzmx> list = new ArrayList<Bgjhhzmx>();
                    for (Bgjhhzmx bgjhhzmx : ycgdmx.getBgjhhzmxList()) {
                        list.add(bgjhhzmx);
                    }
                    cgdmx.setBgjhhzmxList(list);
                    break;
                }
            }
            if (cgdmx.getSbsl() != null && cgdmx.getSbsl() != 0) {
                if (cgdmx.getKh() != null) {
                    khDao.updateKhSlAdd(cgdmx.getKh().getId(), cgdmx.getSbsl());
                }
                cgdmx.setYjs(false);
                cgdmx.setCgjsd(null);
            } else {
                mxlist.remove(cgdmx);
                i--;
                if (mxlist == null)
                    break;
            }
        }
        cgd.setRkr(null);
        cgd.setRksj(null);
        cgd.setCgdmxList(mxlist);
        if (cgd.getCgdmxList() != null && cgd.getCgdmxList().size() > 0)
            this.cgdDao.save(cgd);

        if ("bght".equals(ycgd.getCglx())) {
            String sql = "insert into t_biz_cgd_wg (id,cgd_id,zt,flag,date_created,last_updated) values (seq_biz_cgd_wg.nextval,?,?,?,?,?)";
            cgdDao.executeSQL(sql, ycgd.getId(), 3, 1, new Date(), new Date());
            if (cgd.getCgdmxList() != null && cgd.getCgdmxList().size() > 0) {
                String sql1 = "insert into t_biz_cgd_wg (id,cgd_id,zt,flag,date_created,last_updated) values (seq_biz_cgd_wg.nextval,?,?,?,?,?)";
                cgdDao.executeSQL(sql1, cgd.getId(), 1, 1, new Date(), new Date());

                for (Cgdmx cgdmx : cgd.getCgdmxList()) {
                    for (Bgjhhzmx bgjhhzmx : cgdmx.getBgjhhzmxList()) {
                        if (this.cgdDao.calcCgdmxSbsl(bgjhhzmx.getId(), cgdmx) >= bgjhhzmx.getJhsl())
                            bgjhhzmx.setZt(8);
                        else
                            bgjhhzmx.setZt(7);
                    }
                }
            }
//            String sql2 = "insert into t_biz_cgd_wg (id,cgd_id,zt,flag,date_created,last_updated) values (seq_biz_cgd_wg.nextval,?,?,?,?,?)";
//            cgdDao.executeSQL(sql2, hccgd.getId(), 1, 1, new Date(), new Date());
        }
    }


    private Xsd operateHcXsd(Xsd yxsd) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Xsd hcxsd = new Xsd();
        ReflectionUtils.getInstance(hcxsd, yxsd);
        initXsd(hcxsd);

        hcxsd.setId(null);
        hcxsd.setYjs(false);
        hcxsd.setXsjsd(null);
        List<Xsmx> xsmxList = yxsd.getXsmxList();
        List<Glfy> xsfyList = yxsd.getXsfyList();

        List<Xsmx> hcxsmxList = new ArrayList<Xsmx>();
        List<Glfy> hcglfyList = new ArrayList<Glfy>();

        for (Xsmx xsmx : xsmxList) {
            Xsmx hcxsmx = new Xsmx();
            PropertyUtils.copyProperties(hcxsmx, xsmx);
            hcxsmx.setId(null);
            hcxsmx.setYjs(false);
            hcxsmx.setXsjsd(null);
            if (xsmx.getSbsl() != null)
                hcxsmx.setSbsl(0 - xsmx.getSbsl());
            if (hcxsmx.getCk_js() != null)
                hcxsmx.setCk_js(0 - xsmx.getCk_js());
            hcxsmx.setMxh(xsmx.getMxh());
            hcxsmx.setCk_sbsl(0 - xsmx.getCk_sbsl());
            hcxsmx.setCreateUser(YgService.getCurrentYg());
            hcxsmx.setCreateOrgan(hcxsd.getSbgs());
            hcxsmx.setCreateDepartment(hcxsd.getSbbm());
            hcxsmx.setDateCreated(new Date());
            hcxsmx.setLastUpdated(hcxsmx.getDateCreated());

            hcxsmxList.add(hcxsmx);
        }
        for (Glfy cgfy : xsfyList) {
            Glfy hccgfy = new Glfy();
            PropertyUtils.copyProperties(hccgfy, cgfy);
            hccgfy.setId(null);
            hccgfy.setJfsl(0 - cgfy.getJfsl());
            hccgfy.setJe(0 - cgfy.getJe());
            hccgfy.setCreateUser(YgService.getCurrentYg());
            hccgfy.setCreateOrgan(hcxsd.getSbgs());
            hccgfy.setCreateDepartment(hcxsd.getSbbm());
            hccgfy.setDateCreated(new Date());
            hccgfy.setLastUpdated(hccgfy.getDateCreated());
            if (cgfy.getGlfymxList() != null) {
                List<Glfymx> gylfymxList = new ArrayList<Glfymx>();
                for (Glfymx glfymx : hccgfy.getGlfymxList()) {
                    Glfymx hcglfymx = new Glfymx();
                    PropertyUtils.copyProperties(hcglfymx, glfymx);
                    hcglfymx.setId(null);
                    hcglfymx.setJtfy(0 - glfymx.getJtfy());
                    hcglfymx.setJsjtfy(0 - glfymx.getJsjtfy());
                    hcglfymx.setGlfy(hccgfy);
                    gylfymxList.add(hcglfymx);
                }
                hccgfy.setGlfymxList(gylfymxList);
            }
            hcglfyList.add(hccgfy);
        }

        //保存红冲的采购单
        hcxsd.setXsdh(this.bmService.getCgdbm(hcxsd.getXslx()));
        hcxsd.setSftzd(true);
        hcxsd.setXsmxList(hcxsmxList);
        hcxsd.setXsfyList(hcglfyList);
        hcxsd.setCksj(new Date());
        hcxsd.setCreateUser(YgService.getCurrentYg());
        hcxsd.setCreateOrgan(yxsd.getSbgs());
        hcxsd.setCreateDepartment(yxsd.getSbbm());
        hcxsd.setDateCreated(new Date());
        hcxsd.setLastUpdated(hcxsd.getDateCreated());
        hcxsd.setYxsd(yxsd);
        this.xsdDao.save(hcxsd);
        return hcxsd;
    }

    private void initXsd(Xsd xsd) {
        if (xsd.getXsht() != null && xsd.getXsht().getId() == null) {
            xsd.setXsht(null);
        }
        if (xsd.getLj() != null && xsd.getLj().getId() == null) {
            xsd.setLj(null);
        }
        if (xsd.getKh() != null && xsd.getKh().getId() == null) {
            xsd.setKh(null);
        }
        if (xsd.getThck() != null && xsd.getThck().getId() == null) {
            xsd.setThck(null);
        }
        if (xsd.getGc() != null && xsd.getGc().getId() == null) {
            xsd.setGc(null);
        }
        if (xsd.getFyzr() != null && xsd.getFyzr().getId() == null) {
            xsd.setFyzr(null);
        }
        if (xsd.getXsgs() != null && xsd.getXsgs().getId() == null) {
            xsd.setXsgs(null);
        }
        if (xsd.getXsbm() != null && xsd.getXsbm().getId() == null) {
            xsd.setXsbm(null);
        }
        if (xsd.getXsr() != null && xsd.getXsr().getId() == null) {
            xsd.setXsr(null);
        }
        if (xsd.getXbgs() != null && xsd.getXbgs().getId() == null) {
            xsd.setXbgs(null);
        }
        if (xsd.getXbbm() != null && xsd.getXbbm().getId() == null) {
            xsd.setXbbm(null);
        }
        if (xsd.getXsmxList() != null) {
            for (Xsmx xsmx : xsd.getXsmxList()) {

                if (xsmx.getJzfs() != null && xsmx.getJzfs().getId() == null) {
                    xsmx.setJzfs(null);
                }
                if (xsmx.getKh() != null && xsmx.getKh().getId() == null) {
                    xsmx.setKh(null);
                }
            }
        }
    }


    /**
     * 通过统付统购的采购单生成内部采购和销售单
     *
     * @param cgd
     */
    @Transactional
    public void createTpdj(Cgd cgd) {
        //确定是统配合同

        if (!"tpcght".equals(cgd.getCglx())) {
            return;
        } else if (cgd.getCght().getWzjh() == null
                || ((Tpwzjh) cgd.getCght().getWzjh()).getTcfs() == null
                || !((Tpwzjh) cgd.getCght().getWzjh()).getTcfs().getZ().equals("统付统购")) {
            return;
        }


        //确定申报公司和采购公司不同，主要应对与总部自己统配的情况
        if (cgd.getCggs() == cgd.getSbgs()) {
            return;
        }

        //生成申报公司对采购公司的采购单
        this.cgdDao.save(createNbCgd(cgd, "统配内部生成采购单"));


        //生成采购公司对申报公司的销售单
        this.xsdDao.save(createNbXsd(cgd, "统配内部生成销售单"));
    }

    /**
     * 通过统付统购的采购单生成内部采购和销售单
     *
     * @param cgd
     */
    @Transactional
    public void createZddhdj(Cgd cgd) {
        //确定是统配合同

        if (!"zddh".equals(cgd.getCglx())) {
            return;
        } else if (cgd.getXsd() == null) {
            return;
        }


        //确定申报公司和采购公司不同，主要应对与总部自己统配的情况
        if (cgd.getCggs().getId().equals(cgd.getXsd().getXsgs().getId())) {
            return;
        }

        //生成申报公司对采购公司的采购单
        this.cgdDao.save(createNbCgd(cgd, "直达到货内部生成采购单"));


        //生成采购公司对申报公司的销售单
        this.xsdDao.save(createNbXsd(cgd, "直达到货内部生成销售单"));
    }

    private Xsd createNbXsd(Cgd cgd, String bz) {
        Xsd xsdnb = new Xsd();
        xsdnb.setXsdh(bmService.getXsdbm("nbxs"));
        xsdnb.setDateCreated(new Date());
        xsdnb.setZt("ysp");
        xsdnb.setCreateUser(cgd.getCreateUser());
        xsdnb.setCreateOrgan(cgd.getCreateOrgan());
        xsdnb.setCreateDepartment(cgd.getCreateDepartment());
        xsdnb.setLastUpdated(xsdnb.getDateCreated());
        xsdnb.setFhsj(xsdnb.getDateCreated());
        xsdnb.setFyzr(sjzdzService.findSjzdzByMc("自提"));
        xsdnb.setYck(true);
//        xsdnb.setYjs(false);
        xsdnb.setBz(bz);
        xsdnb.setXsgs(cgd.getCggs());
        xsdnb.setSbgs(cgd.getCggs());
        xsdnb.setSbr(cgd.getSbr());
        xsdnb.setXslx("htxs");
        xsdnb.setSxsj(cgd.getCgsj());
        xsdnb.setDsyfje(cgd.getDsyfje());
        xsdnb.setThck(cgd.getDzck());
        xsdnb.setJhsj(cgd.getFhrq());
        xsdnb.setGlId(cgd.getId());
        xsdnb.setKh(cgd.getSbgs());
        xsdnb.setSfnb(true);
        xsdnb.setSl(Double.parseDouble(cgd.getSl()));
        xsdnb.setYsh(true);

        xsdnb.setXsmxList(createXsdmxByCgd(xsdnb, cgd, null));
        return xsdnb;
    }

    private Cgd createNbCgd(Cgd cgd, String bz) {
        Cgd cgdnb = new Cgd();
        cgdnb.setCgdh(bmService.getCgdbm("nbcg"));
        cgdnb.setDateCreated(new Date());
        cgdnb.setLastUpdated(cgdnb.getDateCreated());
        cgdnb.setZt("ysp");
        cgdnb.setCreateUser(cgd.getCreateUser());
        cgdnb.setCreateOrgan(cgd.getCreateOrgan());
        cgdnb.setCreateDepartment(cgd.getCreateDepartment());
        cgdnb.setYrk(true);
//        cgdnb.setYjs(false);
        cgdnb.setBz(bz);
        cgdnb.setCggs(cgd.getSbgs());
        cgdnb.setSbgs(cgd.getSbgs());
        cgdnb.setSbbm(cgd.getSbbm());
        cgdnb.setSbr(cgd.getSbr());
        cgdnb.setCglx("cgrk");
        cgdnb.setCgsj(cgd.getCgsj());
        cgdnb.setCyh(cgd.getCyh());
        cgdnb.setDsyfje(cgd.getDsyfje());
        cgdnb.setDzck(cgd.getDzck());
        cgdnb.setFhgs(cgd.getFhgs());
        cgdnb.setFhrq(cgd.getFhrq());
        cgdnb.setGlId(cgd.getId());
        cgdnb.setGys(cgd.getCggs());
        cgdnb.setJhdhrq(cgd.getJhdhrq());
        cgdnb.setSfnb(true);
        cgdnb.setSl(cgd.getSl());
        cgdnb.setYsh(true);
        cgdnb.setCgdmxList(createCgdmxByCgd(cgdnb, cgd));
        return cgdnb;
    }

    private List<Cgdmx> createCgdmxByCgd(Cgd cgdnb, Cgd cgd) {
        List<Cgdmx> cgdmxes = new ArrayList<Cgdmx>();
        for (Cgdmx cgdmx : cgd.getCgdmxList()) {
            Cgdmx mx = new Cgdmx();
            mx.setId(null);
            mx.setGg(cgdmx.getGg());
            mx.setCd(cgdmx.getCd());
            mx.setJs(cgdmx.getJs());
            mx.setJzfs(cgdmx.getJzfs());
            mx.setSbsl(cgdmx.getSbsl());
            mx.setRkjs(cgdmx.getRkjs());
            mx.setRksl(cgdmx.getRksl());
            mx.setRkjz(cgdmx.getRkjz());
            mx.setBz(cgdmx.getBz());
            mx.setKh(cgdmx.getKh());
            mx.setBhsj(CalcUtils.calcKccb(cgdmx));
            mx.setHsj(CalcUtils.clacHbl(cgdmx.getBhsj(), Double.parseDouble(cgd.getSl())));
            mx.setCgd(cgdnb);
            mx.setLastUpdated(new Date());
            cgdmxes.add(mx);
        }
        return cgdmxes;
    }


    @Transactional
    public String findCgdSearch(String cgdh, Date fhrqStart, Date fhrqEnd, Long cgjsdId, Long cggsId, Long gysId, int pageNo, int pageSize) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page cgdPage = this.cgdDao.findCgdSearch(cgdh, fhrqStart, fhrqEnd, cgjsdId, cggsId, gysId, pageNo, pageSize);
        String cgdJson = gson.toJson(cgdPage.getResult());
        return "{\"total\":" + cgdPage.getTotalCount() + ",\"rows\":" + cgdJson + "}";
    }


    @Transactional
    public String findCgddmxSearch(Long cgjsdId) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        /*     String result = "";
     Double sbsl = 0d;
     Double hsj = 0d;
     Double bhsj = 0d;
     Double je = 0d;
     Double se = 0d;
     Double ce = 0d;*/
        List<Map> cgdmxList = this.cgdDao.findCgdmxSearch(cgjsdId);
        /*     if (cgdmxList.size() > 0) {
            for (Map map : cgdmxList) {
                sbsl += map.get("sbsl") == null ? 0d : Double.parseDouble(map.get("sbsl").toString());
                hsj += map.get("hsj") == null ? 0d : Double.parseDouble(map.get("hsj").toString());
                bhsj += map.get("bhsj") == null ? 0d : Double.parseDouble(map.get("bhsj").toString());
                je += map.get("je") == null ? 0d : Double.parseDouble(map.get("je").toString());
                se += map.get("se") == null ? 0d : Double.parseDouble(map.get("se").toString());
                ce += map.get("ce") == null ? 0d : Double.parseDouble(map.get("ce").toString());
            }
            result = "{\"rows\":" + gson.toJson(cgdmxList) + ",\"footer\":[{\"cgdh\":\"合计:\",\"sbsl\":" + sbsl
                    + ",\"hsj\":" + hsj + ",\"bhsj\":" + bhsj + ",\"je\":" + je + ",\"se\":" + se + ",\"ce\":" + ce + "}]}";
        } else {
            result = "{\"rows\":" + gson.toJson(cgdmxList) + "}";
        }*/
        return gson.toJson(cgdmxList);
    }


    @Transactional
    public String findCgdmxSearch(Long cgjsdId) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
        String result = StringUtils.EMPTY;
        Double ddfy = 0d;
        Double me = 0d;
        Double je = 0d;
        Double se = 0d;
        Double ce = 0d;
        Jsd cgjsd = this.cgjsdDao.get(cgjsdId);
        List<Map> cgdmxList = new ArrayList<Map>();
        if (cgjsd.getZt() == 3) {
            cgdmxList = this.cgjsdmxDao.findCgjsdmxSearch(cgjsdId);
        } else
            cgdmxList = this.cgdDao.findCgdmxSearch(cgjsdId);
        if (cgdmxList.size() > 0) {
            for (Map map : cgdmxList) {
                ddfy = map.get("ddfy") == null ? 0d : Double.parseDouble(map.get("ddfy").toString());
//                Double hsj = map.get("hsj") == null ? 0d : Double.parseDouble(map.get("hsj").toString());
//                Double rksl = map.get("rksl") == null ? 0d : Double.parseDouble(map.get("rksl").toString());
                me = map.get("me") == null ? 0d : Double.parseDouble(map.get("me").toString());
                je += map.get("je") == null ? 0d : Double.parseDouble(map.get("je").toString());
                se += map.get("se") == null ? 0d : Double.parseDouble(map.get("se").toString());
                ce += map.get("ce") == null ? 0d : Double.parseDouble(map.get("ce").toString());
            }
            result = "{\"rows\":" + gson.toJson(cgdmxList) + ",\"footer\":[{\"cgdh\":\"代垫运费(元):\",\"wzgg.code\":" + df.format(ddfy)
                    + ",\"wzgg.ggxh\":\"净余额(元):\",\"wzgg.dw\":" + df.format(je) + ",\"rksl\":\"税额(元):\", \"hsj\":" + df.format(se) + ",\"bhsj\":\"面额(元):\", \"je\":" + df.format(me) + ", \"ce\":" + df.format(ce) + "}]}";
        } else {
            result = "{\"rows\":" + gson.toJson(cgdmxList) + "}";
        }
        return result;
    }

    @Transactional
    public String findGysByCgd(Long cggsId, Long sbgsId, String gysJc) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        List<Map> gysList = this.cgdDao.findGysByCgd(cggsId, sbgsId, gysJc);
        String gysJson = gson.toJson(gysList);
        return gysJson;
    }

    @Transactional
    public String findJz(Long ggId, Long cd) {
        Gg gg = new Gg();
        if (ggId != null) {
            gg = ggDao.get(ggId);
        }
        String cdz = sjzdzService.findSjzdzDetail(cd).getZ();
        String jz = this.ggDao.findJzByPro(gg, cdz);
        return "{'jz':'" + jz + "'}";
    }

    @Transactional
    public String findCgdmxByCgdId(Long cgdId, Double ce) {
        Gson gson = new Gson();
        List<Map> cgdmxList = this.cgdDao.findCgmx(cgdId);
        Double sbsl = 0d;
        //Double average_je = 0d;
        Double zjbc_je = 0d;
        if (cgdmxList.size() > 0) {
            for (Map map : cgdmxList) {
                sbsl += map.get("sbsl") == null ? 0d : (Double) map.get("sbsl");
            }
            //average_je = ce / sbsl;
            for (Map map : cgdmxList) {
                zjbc_je = (Double) map.get("sbsl") * ce / sbsl;
                map.put("je", zjbc_je);
            }
        }
        return gson.toJson(cgdmxList);
    }

    @Autowired
    public void setCgdDao(CgdDao cgdDao) {
        this.cgdDao = cgdDao;
    }

    @Autowired
    public void setShjDao(ShjDao shjDao) {
        this.shjDao = shjDao;
    }

    @Autowired
    public void setKhService(KhService khService) {
        this.khService = khService;
    }

    @Autowired
    public void setXsdDao(XsdDao xsdDao) {
        this.xsdDao = xsdDao;
    }

    @Transactional
    public void add(Cgd cgd) {
        java.text.DecimalFormat jtdf = new java.text.DecimalFormat("#0.00");
        java.text.DecimalFormat df = new java.text.DecimalFormat("#0.0000");
        initCgd(cgd);
        //处理关联销售单
        operateXsd(cgd);

        cgd.setZt("ybc");
        if (cgd.getSl() != null) {
            String sl = df.format(Double.parseDouble(cgd.getSl()));
            cgd.setSl(sl);
        }
        cgd.setCreateUser(YgService.getCurrentYg());
        cgd.setCreateOrgan(YgService.getCurrentYg().getZggs());
        cgd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        cgd.setLastUpdated(cgd.getDateCreated());
        if (cgd.getCgdmxList() != null && cgd.getCgdmxList().size() > 0) {
            Long count = 0l;
            for (Cgdmx cgdmx : cgd.getCgdmxList()) {

                if (cgdmx.getBhsj() != null) {
                    String bhsj = df.format(cgdmx.getBhsj());
                    cgdmx.setBhsj(Double.valueOf(bhsj));
                }
                if (cgdmx.getBhse() != null) {
                    String bhse = jtdf.format(cgdmx.getBhse());
                    cgdmx.setBhse(Double.valueOf(bhse));
                }
                if (cgdmx.getHsj() != null) {
                    String hsj = df.format(cgdmx.getHsj());
                    cgdmx.setHsj(Double.valueOf(hsj));
                }
                if (cgdmx.getHse() != null) {
                    String hse = jtdf.format(cgdmx.getHse());
                    cgdmx.setHse(Double.valueOf(hse));
                }
                if (cgdmx.getMxh() == null) {
                    cgdmx.setMxh(count + 1);
                }
                cgdmx.setCreateUser(YgService.getCurrentYg());
                cgdmx.setCreateOrgan(cgd.getSbgs());
                cgdmx.setCreateDepartment(cgd.getSbbm());
                cgdmx.setDateCreated(new Date());
                cgdmx.setLastUpdated(cgdmx.getDateCreated());
                count++;
            }
        }
        if (cgd.getCgfyList() != null && cgd.getCgfyList().size() != 0) {
            for (Glfy glfy : cgd.getCgfyList()) {
                String je = jtdf.format(glfy.getJe());
                glfy.setJe(Double.valueOf(je));
                glfy.setDateCreated(new Date());
                glfy.setLastUpdated(new Date());
                glfy.setCreateUser(YgService.getCurrentYg());
                glfy.setCreateOrgan(cgd.getSbgs());
                glfy.setCreateDepartment(cgd.getSbbm());
                glfyDao.save(glfy);
            }
        }
        this.cgdDao.save(cgd);
    }

    @Transactional
    public void operateXsd(Cgd cgd) {
        Cght cght = cghtDao.get(cgd.getCght().getId());
        if ("zddh".equals(cgd.getCglx()) && !"保兑仓".equals(cght.getRzlx().getMc())) {
            saveXsdBycgd(cgd);
        } else {
            cgd.setXsd(null);
        }
    }

    @Transactional
    public void saveXsdBycgd(Cgd cgd) {
        Xsd tempXsd = cgd.getXsd();
        if (tempXsd.getId() != null) {
            Xsd saveXsd = this.xsdDao.get(tempXsd.getId());
            Xsht xsht = this.xshtDao.get(saveXsd.getXsht().getId());
            saveXsd.setThr(tempXsd.getThr());
            saveXsd.setXsmxList(createXsdmxByCgd(saveXsd, cgd, xsht));
            cgd.setXsd(saveXsd);
            saveXsd.setLastUpdated(new Date());
            this.xsdDao.save(saveXsd);
        } else {
            Xsd saveXsd = tempXsd;
            Xsht xsht = this.xshtDao.get(saveXsd.getXsht().getId());
            saveXsd.setXsgs(tempXsd.getXsgs());
            saveXsd.setXsbm(cgd.getCgbm());
            saveXsd.setXsr(cgd.getCgr());
            saveXsd.setSbgs(cgd.getSbgs());
            saveXsd.setSbbm(cgd.getSbbm());
            saveXsd.setLj(xsht.getLj());
            saveXsd.setSbr(cgd.getSbr());
            saveXsd.setSxsj(cgd.getCgsj());
            saveXsd.setFhsj(cgd.getCgsj());
            saveXsd.setFyzr(xsht.getFhzr());
            saveXsd.setSl(xsht.getSl());
            saveXsd.setGc(cgd.getXsd().getGc());
            saveXsd.setDsyfje(cgd.getDsyfje());
            saveXsd.setZt("ybc");
            saveXsd.setXslx("zddh");
            saveXsd.setXsdh(xsdService.xsdBm(saveXsd));
            saveXsd.setXsmxList(createXsdmxByCgd(saveXsd, cgd, xsht));
            saveXsd.setCreateUser(YgService.getCurrentYg());
            saveXsd.setCreateOrgan(YgService.getCurrentYg().getZggs());
            saveXsd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            saveXsd.setDateCreated(new Date());
            saveXsd.setLastUpdated(saveXsd.getDateCreated());
            this.xsdDao.save(saveXsd);
        }
    }

    @Transactional
    public void transferXsd(Long xsdId) {
        Xsd xsd = this.xsdDao.get(xsdId);
        Cgd cgd = this.cgdDao.findUniqueByProperty("xsd.id", xsdId);
        if (cgd != null) {
            Xsht xsht = this.xshtDao.get(xsd.getXsht().getId());
            xsd.setXsmxList(createXsdmxByCgd(xsd, cgd, xsht));
            this.xsdDao.save(xsd);
        }
    }

    //生成销售单明细
    public List<Xsmx> createXsdmxByCgd(Xsd xsd, Cgd cgd, Xsht xsht) {
        List<Xsmx> xsmxes = new ArrayList<Xsmx>();
        //Map<Long, Long> map = new HashMap<Long, Long>();
        for (Cgdmx cgdmx : cgd.getCgdmxList()) {
            Xsmx xsmx = new Xsmx();
            xsmx.setJtwz(cgdmx.getGg());
            xsmx.setJs(cgdmx.getJs());
            xsmx.setXscb(CalcUtils.calcKccb(cgdmx, cgd));
            xsmx.setJzfs(cgdmx.getJzfs());
            xsmx.setMxh(cgdmx.getMxh());
            Htmx htmx = findHtmx(cgdmx, xsht);
            if (htmx != null) {
                xsmx.setHsj(Double.parseDouble(htmx.getHsj().toString()));
                xsmx.setBhsj(Double.parseDouble(htmx.getBhsj().toString()));
            } else {
                xsmx.setBhsj(CalcUtils.calcKccb(cgdmx, cgd));
                xsmx.setHsj(CalcUtils.clacHbl(xsmx.getBhsj(), Double.parseDouble(cgd.getSl())));
            }
            xsmx.setCk(cgdmx.getCk());
            xsmx.setSbsl(cgdmx.getSbsl());
            xsmx.setBz(cgdmx.getBz());
            xsmx.setDateCreated(new Date());
            xsmx.setLastUpdated(xsmx.getDateCreated());
            xsmx.setCreateUser(YgService.getCurrentYg());
            xsmx.setCreateOrgan(xsd.getCreateOrgan());
            xsmx.setCreateDepartment(xsd.getCreateDepartment());
            xsmx.setXsd(xsd);
            xsmxes.add(xsmx);
        }
        return xsmxes;
    }

    private Htmx findHtmx(Cgdmx cgdmx, Xsht xsht) {
        if (xsht != null) {
            for (Htmx htmx : xsht.getHtmxList()) {
                if (htmx.getWzgg().getId().equals(cgdmx.getGg().getId()) && htmx.getMxh().equals(cgdmx.getMxh())) {
                    return htmx;
                }
            }
        }

        return null;
    }


    @Transactional
    public void delete(Cgd cgd) {
        cgd = this.cgdDao.get(cgd.getId());
        if (cgd.getCgjsd() != null) {
            throw new RuntimeException("禁止删除！该采购单已结算");
        }
//        cgd.setCreateUser(YgService.getCurrentYg());
        cgd.setLastUpdated(new Date());
        cgd.setDeleted(1);
        if (cgd.getCgdmxList() != null && cgd.getCgdmxList().size() != 0) {
            for (Cgdmx cgdmx : cgd.getCgdmxList()) {
                cgdmx.setDeleted(1);
                cgdmx.setLastUpdated(new Date());
                cgdmxDao.save(cgdmx);
            }
        }
        if (cgd.getCgfyList() != null && cgd.getCgfyList().size() != 0) {
            for (Glfy glfy : cgd.getCgfyList()) {
                glfy.setDeleted(1);
                glfy.setLastUpdated(new Date());
                glfyDao.save(glfy);
            }
        }
        try {
            if (cgd.getXsd() != null && cgd.getXsd().getId() != null) {
                Xsd xsd = cgd.getXsd();
                xsd = this.xsdDao.get(xsd.getId());
//                xsd.setCreateUser(YgService.getCurrentYg());
                xsd.setDeleted(1);
                xsd.setLastUpdated(cgd.getLastUpdated());
                if (xsd.getXsmxList() != null && xsd.getXsmxList().size() != 0) {
                    for (Xsmx xsmx : xsd.getXsmxList()) {
                        xsmx.setDeleted(1);
                        xsmx.setLastUpdated(new Date());
                        xsmxDao.save(xsmx);
                    }
                }
                if (xsd.getXsfyList() != null && xsd.getXsfyList().size() != 0) {
                    for (Glfy glfy : xsd.getXsfyList()) {
                        glfy.setDeleted(1);
                        glfy.setLastUpdated(new Date());
                        glfyDao.save(glfy);
                    }
                }
            }
        } catch (Exception e) {

        }
        this.cgdDao.save(cgd);
    }

    public Cgd findById(Long id) {
        return this.cgdDao.get(id);
    }

    public Cgd findByCgdmxId(Long id) {
        return cgdDao.get(cgdDao.findCgdByCgdmxId(id));
    }

    public List<Map> findCgmx(Long id) {
        return this.cgdDao.findCgmx(id);
    }

    public String findCgdJszt(Cgd cgd) {
        String jszt = StringUtils.EMPTY;
        for (int i = 0; i < cgd.getCgdmxList().size(); i++) {
            Cgdmx cgdmx = cgd.getCgdmxList().get(i);
            if (i == 0) {
                if (cgdmx.getYjs() == null || !cgdmx.getYjs()) {
                    jszt = "未结算";
                } else {
                    jszt = "已结算";
                }
            } else {
                if (jszt.equals("未结算") && cgdmx.getYjs()) {
                    jszt = "部分结算";
                    break;
                } else if (jszt.equals("已结算") && (cgdmx.getYjs() == null || !cgdmx.getYjs())) {
                    jszt = "部分结算";
                    break;
                }
            }
        }
        return jszt;
    }

    /**
     * 采购结算查询采购单明细
     *
     * @param id
     * @return
     */
    public List<Map> findCgjsdSearchCgmx(Long id) {
        return this.cgdDao.findCgjsdSearchCgmx(id);
    }


    public List<Map> findCgmxByKh(Kh kh) {
        return this.cgdDao.findCgmxByKh(kh);
    }

    public List<Map> findCgfy(Long id) {
        return this.cgdDao.findCgfy(id);
    }

    @Transactional
    public void check(Cgd cgd) throws SQLException {
        Cgd ysCgd = this.cgdDao.get(cgd.getId());
        if (cgd.getFhgs().getId() != null) {
            ysCgd.setFhgs(cgd.getFhgs());
        }
        ysCgd.setSfys(true);
        ysCgd.setYsr(YgService.getCurrentYg());
        ysCgd.setYsrq(new Date());
        ysCgd.setLastUpdated(new Date());
        initCgd(ysCgd);
        this.cgdDao.save(ysCgd);
    }


    //入库明细
    public String findrkmx(Long id) {
        Gson gson = new Gson();
        List<Map> rkmxList = this.cgdDao.findrkmxList(id);
        String json = gson.toJson(rkmxList);
        return "{\"rows\":" + json + "}";
    }

    //入库明细详细
    public String findrkmxDetail(Long id) {
        Gson gson = new Gson();
        List<Map> rkmxList = this.cgdDao.findrkmxDetailList(id);
        String json = gson.toJson(rkmxList);
        return "{\"rows\":" + json + "}";
    }

    //todo
    @Transactional
    public synchronized void stock(Cgd cgd) throws RuntimeException, SQLException {
        if (this.findById(cgd.getId()) != null && this.findById(cgd.getId()).getYrk()) {
            throw new RuntimeException("此采购单已入库，无需入库!");
        }
        List<Cgdmx> cgdmxes = cgd.getCgdmxList();//从前台拿到的采购单明细

        Cgd saveCgd = this.cgdDao.get(cgd.getId());

        if (saveCgd.getEndFlag()) {
            saveCgd.setYrk(true);
            saveCgd.setZt("ysp");
        } else {
            saveCgd.setYrk(false);
            saveCgd.setZt("ytj");
        }


        saveCgd.setRkr(YgService.getCurrentYg());
        saveCgd.setLastUpdated(new Date());
        saveCgd.setRksj(new Date());
        saveCgd.setFjList(cgd.getFjList());
        initCgd(saveCgd);
        String pxhSource = khDao.findKhByCgd(saveCgd);
        Integer pxh = Integer.parseInt(pxhSource);
        for (Cgdmx cgdmx : cgdmxes) {
            cgdmx.setXsxt_xsdh("XSXT020150919-"+ String.valueOf(System.currentTimeMillis()));
            if (cgdmx.getRksl() == 0) {
                continue;
            }
            ++pxh;
            createKhByCgdmx(saveCgd, cgdmx, cgdmxes, pxh);
        }
        //生成多余货权的卡号
        List<Cgdmx> cgdmxList = saveCgd.getCgdmxList();
        for (Cgdmx ycgdmx : cgdmxList) {
            List<Map> maps = this.countRkmxFromCgdmx(ycgdmx.getId(), cgdmxes);
            Integer sumRkjs = (Integer) maps.get(0).get("sumRkjs");
            Double sumRksl = (Double) maps.get(1).get("sumRksl");
            if (sumRksl < ycgdmx.getSssl()) {
                ++pxh;
                createExcessKhByCgdmx(saveCgd, ycgdmx, cgdmxes, pxh, sumRkjs, sumRksl);
            }
            ycgdmx.setMxh(ycgdmx.getMxh() + cgdmxes.size());
            this.cgdmxDao.save(ycgdmx);
        }
//        //生成商权货权通知的参数
//      String json = createStockArgs(saveCgd, cgdmxes);
//        //调用接口传递参数
//        String result = this.webserviceTransService.transKhWebServiceArgs(json);
//
//        if (result != null) {
//            Gson gson = new Gson();
//            Map<String, Object> resultMap = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
//            }.getType());
//            if (resultMap != null && resultMap.get("code").equals("0")) {
//                this.cgdDao.save(saveCgd);
//                createTpdj(saveCgd);
//                if (saveCgd.getCgfyList() != null) {
//                    List<Glfy> glfyList = saveCgd.getCgfyList();
//                    java.text.DecimalFormat df2 = new java.text.DecimalFormat("#0.00");
//                    Double sumSl = sumSl(cgdmxes);
//                    Double sumJtfy = 0d;
//                    for (Glfy glfy : glfyList) {
//                        for (int i = 0; i < cgdmxes.size(); i++) {
//                            if (i < cgdmxes.size() - 1) {
//                                Glfymx glfymx = new Glfymx();
//                                glfymx.setGg(cgdmxes.get(i).getGg());
//                                glfymx.setCgdmx(cgdmxes.get(i));
//                                glfymx.setGlfy(glfy);
//                                glfymx.setJtfy(Double.valueOf(df2.format(glfy.getJe() / sumSl * cgdmxes.get(i).getRksl())));
//                                glfymx.setDateCreated(new Date());
//                                glfymx.setLastUpdated(glfymx.getDateCreated());
//                                glfymx.setCreateUser(YgService.getCurrentYg());
//                                glfymx.setCreateOrgan(YgService.getCurrentYg().getZggs());
//                                glfymx.setCreateDepartment(YgService.getCurrentYg().getZgjg());
//                                glfymxDao.save(glfymx);
//                                sumJtfy += Double.valueOf(df2.format(glfymx.getJtfy()));
//                            } else if (i == cgdmxes.size() - 1) {
//                                Glfymx glfymx = new Glfymx();
//                                glfymx.setGg(cgdmxes.get(i).getGg());
//                                glfymx.setCgdmx(cgdmxes.get(i));
//                                glfymx.setGlfy(glfy);
//                                glfymx.setJtfy(Double.valueOf(df2.format(glfy.getJe() - sumJtfy)));
//                                glfymx.setDateCreated(new Date());
//                                glfymx.setLastUpdated(glfymx.getDateCreated());
//                                glfymx.setCreateUser(YgService.getCurrentYg());
//                                glfymx.setCreateOrgan(YgService.getCurrentYg().getZggs());
//                                glfymx.setCreateDepartment(YgService.getCurrentYg().getZgjg());
//                                glfymxDao.save(glfymx);
//                            }
//                        }
//                        sumJtfy = 0d;
//                        glfy.setLastUpdated(new Date());
//                        glfyDao.save(glfy);
//                    }
//                }
//                if ("bght".equals(saveCgd.getCglx())) {
//                    String sql = "insert into t_biz_cgd_wg (id,cgd_id,zt,flag,date_created,last_updated) values (seq_biz_cgd_wg.nextval,?,?,?,?,?)";
//                    cgdDao.executeSQL(sql, cgd.getId(), 2, 1, new Date(), new Date());
//                }
//            } else {
//                throw new RuntimeException((String) resultMap.get("message"));
//            }
//        } else {
//            throw new RuntimeException("入库到仓储接口失败,请重新提交");
//        }
    }

    public List<Map> countRkmxFromCgdmx(Long id, List<Cgdmx> cgdmxList) {
        Integer sumRkjs = 0;
        Double sumRksl = 0d;
        for (Cgdmx cgdmx : cgdmxList) {
            if (cgdmx.getId().equals(id)) {
                sumRkjs += (cgdmx.getRkjs() == null) ? 0 : cgdmx.getRkjs();
                sumRksl += (cgdmx.getRksl() == null) ? 0d : cgdmx.getRksl();
            }
        }
        List<Map> maps = new ArrayList<Map>();
        Map<String, Integer> map1 = new HashMap<String, Integer>();
        map1.put("sumRkjs", sumRkjs);
        Map<String, Double> map2 = new HashMap<String, Double>();
        map2.put("sumRksl", sumRksl);
        maps.add(map1);
        maps.add(map2);
        return maps;
    }

    /**
     * 根据明细生成卡号
     *
     * @param saveCgd
     * @param cgdmx
     * @param cgdmxes
     */
    public void createKhByCgdmx(Cgd saveCgd, Cgdmx cgdmx, List<Cgdmx> cgdmxes, int pxh) {
        Kh kh = new Kh();
        kh.setKhbm(bmService.getKckhbm(saveCgd.getDzck().getId()));
        kh.setJtwz(cgdmx.getGg());
        kh.setCggs(saveCgd.getCggs());
        Bgjhmx bgjhmx = bgjhmxDao.get(cgdmx.getKh().getBgjhmx().getId());
        Bgjh bgjh = bgjhDao.get(bgjhmx.getBgjh().getId());
        kh.setSbgs(bgjh.getJhdw());
        kh.setCd(cgdmx.getCd());
        kh.setCgd(saveCgd);
        kh.setXsxt_xsdh(cgdmx.getXsxt_xsdh());
        kh.setGys(saveCgd.getGys());
        kh.setSl(cgdmx.getRksl());
        kh.setJs(cgdmx.getRkjs());
        kh.setJz(cgdmx.getRkjz());
        kh.setCshjs(cgdmx.getRkjs());
        kh.setCshsl(cgdmx.getRksl());
        kh.setJhsl(cgdmx.getSbsl());
        kh.setJhjs(cgdmx.getJs());
        kh.setKkdsl(cgdmx.getRksl());
        kh.setWsdj(cgdmx.getBhsj());
        kh.setSku(cgdmx.getSku());
        kh.setCk(saveCgd.getDzck());
        kh.setZlqk("");
        kh.setRkrq(saveCgd.getRksj());
        kh.setBz("");
        kh.setCreateUser(saveCgd.getCreateUser());
        kh.setCreateOrgan(saveCgd.getSbgs());
        kh.setDateCreated(new Date());
        kh.setLastUpdated(kh.getDateCreated());
        kh.setBgjhmx(cgdmx.getKh().getBgjhmx());
        kh.setCgdmx(cgdmx);
        kh.setPxh(pxh);
        kh.setRkdh(saveCgd.getCgdh() + "-" + cgdmxes.get(0).getMxh());
        this.khService.save(kh);
        cgdmx.setKh(kh);
        shjDao.executeShj(kh.getId());
    }

    /**
     * 生成多余反馈数量卡号
     *
     * @param saveCgd
     * @param cgdmx
     * @param cgdmxes
     */
    public void createExcessKhByCgdmx(Cgd saveCgd, Cgdmx cgdmx, List<Cgdmx> cgdmxes, int pxh, int sumRkjs, Double sumRksl) {
        Kh kh = new Kh();
        kh.setKhbm(bmService.getKckhbm(saveCgd.getDzck().getId()));
        kh.setJtwz(cgdmx.getGg());
        kh.setCggs(saveCgd.getSbgs());
        Integer js = cgdmx.getSsjs() - sumRkjs;
        Double sl = cgdmx.getSssl() - sumRksl;
        kh.setSbgs(saveCgd.getSbgs());
        kh.setCd(cgdmx.getCd());
        kh.setCgd(saveCgd);
        kh.setGys(saveCgd.getGys());
        kh.setSl(sl);
        kh.setJs(js);
        kh.setJz(cgdmx.getRkjz());
        kh.setCshjs(js);
        kh.setCshsl(sl);
        kh.setJhsl(sl);
        kh.setJhjs(js);
        kh.setKkdsl(sl);
        kh.setWsdj(cgdmx.getBhsj());
        kh.setSku(cgdmx.getSku());
        kh.setCk(saveCgd.getDzck());
        kh.setZlqk("");
        kh.setRkrq(saveCgd.getRksj());
        kh.setBz("");
        kh.setCreateUser(saveCgd.getCreateUser());
        kh.setCreateOrgan(saveCgd.getSbgs());
        kh.setDateCreated(new Date());
        kh.setLastUpdated(kh.getDateCreated());
        kh.setBgjhmx(null);
        kh.setCgdmx(cgdmx);
        kh.setPxh(pxh);
        kh.setRkdh(saveCgd.getCgdh() + "-" + cgdmxes.get(0).getMxh());
        this.khService.save(kh);
        cgdmx.setKh(kh);
    }

    private Double sumSl(List<Cgdmx> cgdmxList) {
        Double sumSl = 0d;
        for (Cgdmx cgdmx : cgdmxList) {
            sumSl += cgdmx.getRksl() == null ? 0 : cgdmx.getRksl();
        }
        return sumSl;
    }

    private void setCgdIntoCgdmx(Cgd cgd, List<Cgdmx> cgdmxes) {
        for (Cgdmx cgdmx : cgdmxes) {
            cgdmx.setCgd(cgd);
        }
    }

    @Transactional
    private void saveKhs(List<Cgdmx> cgdmxes, Cgd cgd) throws SQLException {
        for (Cgdmx cgdmx : cgdmxes) {
            if (cgdmx.getRksl() == 0) {
                continue;
            }
            Kh kh = new Kh();
            kh.setKhbm(bmService.getKckhbm(cgd.getDzck().getId()));
            kh.setJtwz(cgdmx.getGg());
            kh.setCggs(cgd.getCggs());
            kh.setSbgs(cgd.getSbgs());
            kh.setSbbm(cgd.getSbbm());
            kh.setCd(cgdmx.getCd());
            kh.setCgd(cgd);
            kh.setGys(cgd.getGys());
            kh.setSl(cgdmx.getRksl());
            kh.setJs(cgdmx.getRkjs());
            kh.setJz(cgdmx.getRkjz());
            kh.setKkdsl(cgdmx.getRksl());
            kh.setWsdj(CalcUtils.calcKccb(cgdmx));
            kh.setCk(cgd.getDzck());
            kh.setZlqk("");
            kh.setRkrq(cgd.getRksj());
            kh.setBz("");
            kh.setCreateUser(cgd.getSbr());
            kh.setCreateOrgan(cgd.getSbgs());
            kh.setCreateDepartment(cgd.getSbbm());
            kh.setDateCreated(new Date());
            kh.setLastUpdated(kh.getDateCreated());
            cgdmx.setKh(kh);
            this.khService.save(kh);
        }
    }


    private void initCgd(Cgd cgd) {
        if (cgd.getLj() != null && cgd.getLj().getId() == null) {
            cgd.setLj(null);
        }
        if (cgd.getCght() != null && cgd.getCght().getId() == null) {
            cgd.setCght(null);
        }
        if (cgd.getGys() != null && cgd.getGys().getId() == null) {
            cgd.setGys(null);
        }
        if (cgd.getDzck() != null && cgd.getDzck().getId() == null) {
            cgd.setDzck(null);
        }

        if (cgd.getYsdw() != null && cgd.getYsdw().getId() == null) {
            cgd.setYsdw(null);
        }

        if (cgd.getCggs() != null && cgd.getCggs().getId() == null) {
            cgd.setCggs(null);
        }
        if (cgd.getCgbm() != null && cgd.getCgbm().getId() == null) {
            cgd.setCgbm(null);
        }
        if (cgd.getCgr() != null && cgd.getCgr().getId() == null) {
            cgd.setCgr(null);
        }
        if (cgd.getSbgs() != null && cgd.getSbgs().getId() == null) {
            cgd.setSbgs(null);
        }
        if (cgd.getSbbm() != null && cgd.getSbbm().getId() == null) {
            cgd.setSbbm(null);
        }
        if (cgd.getSbr() != null && cgd.getSbr().getId() == null) {
            cgd.setSbr(null);
        }
        if (cgd.getFhgs() != null && cgd.getFhgs().getId() == null) {
            cgd.setFhgs(null);
        }
        if (cgd.getXsd() != null && cgd.getXsd().getGc() != null && cgd.getXsd().getGc().getId() == null) {
            cgd.getXsd().setGc(null);
        }
        if (cgd.getCgdmxList() != null) {
            for (Cgdmx cgdmx : cgd.getCgdmxList()) {
                if (cgdmx.getJzfs() != null && cgdmx.getJzfs().getId() == null) {
                    cgdmx.setJzfs(null);
                }

                if (cgdmx.getCd() != null && cgdmx.getCd().getId() == null) {
                    cgdmx.setCd(null);
                }
            }
        }

        if (cgd.getCgdh() == null || "".equals(cgd.getCgdh())) {
            cgd.setCgdh(this.bmService.getCgdbm(cgd.getCglx()));
        }
    }

    @Transactional
    public void confirm(Cgd cgd) throws Exception {
        cgd = this.cgdDao.get(cgd.getId());
//        List<Bzj> list = this.bzjService.findBzjByCght(cgd.getCght());
//        List<Bgjh> bgjhs = bgjhDao.findBgjhListByBgjhhzId(cgd.getCght().getBgjhhz().getId());
//        if (list.size() > 0) {
//            //先判断代理客户是否都开具保证金了
//            for (Bgjh bgjh : bgjhs) {
//                Boolean flag = bzjService.checkHtAndXyByBzj(cgd.getCght().getId(), bgjh.getJhdw().getId());
//                if (flag) {
//                    throw new RuntimeException("采购单对应的采购合同中代理客户" + bgjh.getJhdw().getJc() + "没有开具保证金，无法提交");
//                }
//                String cghthj = bzjDao.sumJeFromCghtByKh(cgd.getCght().getId(), bgjh.getJhdw().getId());
//                List<Bzj> bzjs = bzjDao.checkHtAndXyByBzj(cgd.getCght().getId(), bgjh.getJhdw().getId());
//                for (Bzj bzj : bzjs) {
//                    if (bzj.getJe().doubleValue() < (Double.valueOf(cghthj) * bzj.getBzjbl() / 100)) {
//                        throw new RuntimeException("采购单对应的采购合同" + cgd.getCght().getHtbm() + "中代理客户" + bgjh.getJhdw().getJc() + "所缴纳最低的保证金" + bzj.getJe().doubleValue() + "不足" + bzj.getBzjbl() + "%比例，此次采购最低应缴纳" + (Double.valueOf(cghthj) * bzj.getBzjbl() / 100));
//                    }
//                }
//            }
//        } else {
//            throw new RuntimeException("采购单对应的采购合同没有开具保证金，无法提交");
//        }
        //生成调用webservice需要传递的参数
//       if (cgd.getSfgh()) {
//            goodsOrderToStoreHouse(cgd);//放货通知仓储系统
//        } else {
//            cgrkToStoreHouseSystem(cgd);//采购单提交到仓储系统入库
//        }
        cgdDao.gbjkUpdate(cgd.getId());
        cgdDao.gbjkUpdate2(cgd.getId());



    }

    /**
     * 采购单提交到仓储系统入库
     *
     * @param cgd
     */
    public void cgrkToStoreHouseSystem(Cgd cgd) {
        String json = createCgdRk(cgd);
        String result = null;
        Gson gson = new Gson();
        if (result != null) {
            Map<String, Object> resultMap = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
            }.getType());
            if (resultMap != null && resultMap.get("code").equals("0")) {
                cgd.setZt("ytj");
                if ("zddh".equals(cgd.getCglx())) {
                    if (cgd.getXsd() != null) {
                        cgd.getXsd().setZt("ytj");
                        cgd.getXsd().setCwsh(true);
                        cgd.getXsd().setShsj(new Date());
                    }
                }
                cgd.setLastUpdated(new Date());
                this.cgdDao.save(cgd);
                bgshd_wg(cgd);
            } else
                throw new RuntimeException((String) resultMap.get("message"));
        } else
            throw new RuntimeException("提交的采购单到仓库接口失败,请重新提交");
    }

    /**
     * 放货通知仓储系统
     *
     * @param cgd
     */
    public void goodsOrderToStoreHouse(Cgd cgd) {
        String json = createGoodsOrderJsonForCgdCommit(cgd);
        String result = this.webserviceTransService.transXsdWebServiceArgs(json);
        Gson gson = new Gson();
        if (result != null) {
            Map<String, Object> resultMap = gson.fromJson(result, new TypeToken<Map<String, Object>>() {
            }.getType());
            if (resultMap != null && resultMap.get("code").equals("0")) {
                cgd.setZt("yfk");
                if ("zddh".equals(cgd.getCglx())) {
                    if (cgd.getXsd() != null) {
                        cgd.getXsd().setZt("ytj");
                        cgd.getXsd().setCwsh(true);
                        cgd.getXsd().setShsj(new Date());
                    }
                }
                cgd.setLastUpdated(new Date());
                this.cgdDao.save(cgd);
                bgshd_wg(cgd);
            } else
                throw new RuntimeException((String) resultMap.get("message"));
        } else
            throw new RuntimeException("提交的采购单到仓库接口失败,请重新提交");
    }

    /**
     * 此方法是为了采购入库根据是否过户字段判断放货指令
     *
     * @param cgd
     * @return
     */
    private String createGoodsOrderJsonForCgdCommit(Cgd cgd) {
        StringBuffer sb = new StringBuffer();
        sb.append("{\"scontractBillcode\":\"").append(cgd.getCgdh().replaceAll("-", "*")).append("\",");
        sb.append("\"billBillcode\":\"").append(cgd.getCgdh().replaceAll("-", "*")).append("\",");
        sb.append("\"buyerCompany\":\"").append(cgd.getSbgs().getBm()).append("\",");
        sb.append("\"reportCompany\":\"").append(cgd.getSbgs().getBm()).append("\",");
        sb.append("\"transferSign\":\"").append("1").append("\",");
        sb.append("\"goodsNum\":\":goodsNum\",");
        sb.append("\"goodsWeight\":\":goodsWeight\",");
        sb.append("\"scontractPumode\":\"").append("transfer").append("\",");
        sb.append("\"billType\":\"lading\",");
        sb.append("\"status\":\"0\",");
        sb.append("\"memberCode\":\"").append(cgd.getSbgs().getBm()).append("\",\"saleBillCodeViewVoList\":[");
        Integer js = 0;
        Double sl = 0.0;
        for (Cgdmx cgdmx : cgd.getCgdmxList()) {
            sb.append("{\"warehouseName\":\"").append(cgd.getDzck().getBh()).append("\",");
            sb.append("\"productareaName\":\"").append(cgdmx.getCd().getBm()).append("\",");
            sb.append("\"partsnameName\":\"").append(cgdmx.getGg().getPmCode()).append("\",");
            sb.append("\"goodsMaterial\":\"").append(cgdmx.getGg().getCzCode()).append("\",");
            sb.append("\"sku\":\"").append(cgdmx.getSku() == null ? "" : cgdmx.getSku()).append("\",");
            sb.append("\"numberUnit\":\"").append(cgdmx.getGg().getSldw() == null ? "" : cgdmx.getGg().getSldw()).append("\",");
            sb.append("\"weightUnit \":\"").append(cgdmx.getGg().getDw() == null ? "" : cgdmx.getGg().getDw()).append("\",");
            sb.append("\"goodsSpec\":\"").append(cgdmx.getGg().getGgCode()).append("\",");
            sb.append("\"goodsNum\":\"").append(cgdmx.getJs() == null ? 1 : cgdmx.getJs()).append("\",");
            sb.append("\"goodsWeight\":\"").append(cgdmx.getSbsl()).append("\",\"resourceSerialNumbers\":{");
            sb.append("\"resourceSerialNumber\":\"").append(cgd.getCgdh()).append("-").append("1").append("\",");
            sb.append("\"number\":\"").append(cgdmx.getJs() == null ? 1 : cgdmx.getJs()).append("\",");
            sb.append("\"weight\":\"").append(cgdmx.getSbsl()).append("\"}},");
            js += cgdmx.getJs() == null ? 1 : cgdmx.getJs();
            sl += cgdmx.getSbsl();
        }
        sb = sb.deleteCharAt(sb.length() - 1);
        sb.append("]}");
        String json = sb.toString().replaceAll(":goodsNum", js.toString());
        json = json.replaceAll(":goodsWeight", sl.toString());
        return json;
    }


    /**
     * 改变采购单的状态
     *
     * @param cgd
     */
    public void update(Cgd cgd) {
        this.cgdDao.save(cgd);
    }

    /**
     * 物供网站接口，推送送货单信息
     *
     * @param cgd
     */
    private void bgshd_wg(Cgd cgd) {
        if ("bght".equals(cgd.getCglx())) {
            String sql = "insert into t_biz_cgd_wg (id,cgd_id,zt,flag,date_created,last_updated) values (seq_biz_cgd_wg.nextval,?,?,?,?,?)";
            cgdDao.executeSQL(sql, cgd.getId(), 1, 1, new Date(), new Date());
        }
    }

    @Transactional
    public void cancel(Cgd cgd) {
        cgd = this.cgdDao.get(cgd.getId());
        //计算今天的最后一秒，过期的单据禁止取消提交
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        if (cgd.getJhdhrq().before(c.getTime())) {
            throw new RuntimeException("单据已经过期，无法取消！");
        }
        cgd.setZt("ybc");
        if ("zddh".equals(cgd.getCglx())) {
            if (cgd.getXsd() != null) {
                cgd.getXsd().setZt("ybc");
            }
        }
        cgd.setLastUpdated(new Date());
        this.cgdDao.save(cgd);
        if ("bght".equals(cgd.getCglx())) {
            String sql = "insert into t_biz_cgd_wg (id,cgd_id,zt,flag,date_created,last_updated) values (seq_biz_cgd_wg.nextval,?,?,?,?,?)";
            cgdDao.executeSQL(sql, cgd.getId(), 4, 1, new Date(), new Date());
        }
    }

    //取消入库验收
    @Transactional
    public void cancelRkshYs(Cgd rksh) {
        rksh = this.cgdDao.get(rksh.getId());
        rksh.setYsr(null);
        rksh.setYsrq(null);
        rksh.setSfys(false);
        rksh.setLastUpdated(new Date());
        this.cgdDao.save(rksh);
    }

    @Transactional
    public void cgdtzApply(Cgd cgd) {
        cgd = this.cgdDao.get(cgd.getId());
        cgd.setTzsqzt("ysq");
        if ("zddh".equals(cgd.getCglx())) {
            if (cgd.getXsd() != null) {
                cgd.getXsd().setTzsqzt("ysq");
            }
        }
        cgd.setLastUpdated(new Date());
        this.cgdDao.save(cgd);
    }

    @Transactional
    public void cgdtzCancel(Cgd cgd) {
        cgd = this.cgdDao.get(cgd.getId());
        cgd.setTzsqzt("wsq");
        if ("zddh".equals(cgd.getCglx())) {
            if (cgd.getXsd() != null) {
                cgd.getXsd().setTzsqzt("wsq");
            }
        }
        cgd.setLastUpdated(new Date());
        this.cgdDao.save(cgd);
    }

    @Transactional
    public void cgdtzExamine(Cgd cgd) {
        cgd = this.cgdDao.get(cgd.getId());
        cgd.setTzsqzt("ysp");
        if ("zddh".equals(cgd.getCglx())) {
            if (cgd.getXsd() != null) {
                cgd.getXsd().setTzsqzt("ysp");
            }
        }
        cgd.setLastUpdated(new Date());
        this.cgdDao.save(cgd);
    }

//    @Autowired
//    public void setBzjDao(BzjDao bzjDao) {
//        this.bzjDao = bzjDao;
//    }

    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }

    @Autowired
    public void setBmService(BmService bmService) {
        this.bmService = bmService;
    }

    @Autowired
    public void setCghtDao(CghtDao cghtDao) {
        this.cghtDao = cghtDao;
    }

    @Autowired
    public void setXsdService(XsdService xsdService) {
        this.xsdService = xsdService;
    }

    @Autowired
    public void setXshtDao(XshtDao xshtDao) {
        this.xshtDao = xshtDao;
    }

    @Autowired
    public void setGlfymxDao(GlfymxDao glfymxDao) {
        this.glfymxDao = glfymxDao;
    }

    @Autowired
    public void setGlfyDao(GlfyDao glfyDao) {
        this.glfyDao = glfyDao;
    }

    @Autowired
    public void setSjzdzService(SjzdzService sjzdzService) {
        this.sjzdzService = sjzdzService;
    }

//    @Autowired
//    public void setYgService(YgService ygService) {
//        this.ygService = ygService;
//    }

    @Autowired
    public void setCgdmxDao(CgdmxDao cgdmxDao) {
        this.cgdmxDao = cgdmxDao;
    }

    @Autowired
    public void setXsmxDao(XsmxDao xsmxDao) {
        this.xsmxDao = xsmxDao;
    }

    @Autowired
    public void setBgjhDao(BgjhDao bgjhDao) {
        this.bgjhDao = bgjhDao;
    }

    @Autowired
    public void setCgjsdDao(CgjsdDao cgjsdDao) {
        this.cgjsdDao = cgjsdDao;
    }

    @Autowired
    public void setCgjsdmxDao(CgjsdmxDao cgjsdmxDao) {
        this.cgjsdmxDao = cgjsdmxDao;
    }

    @Autowired
    public void setBgjhmxDao(BgjhmxDao bgjhmxDao) {
        this.bgjhmxDao = bgjhmxDao;
    }

    @Autowired
    public void setWebserviceTransService(WebserviceTransService webserviceTransService) {
        this.webserviceTransService = webserviceTransService;
    }

//    @Autowired
//    public void setBzjService(BzjService bzjService) {
//        this.bzjService = bzjService;
//    }

    @Autowired
    public void setGgDao(GgDao ggDao) {
        this.ggDao = ggDao;
    }

//    @Autowired
//    public void setGsjgDao(GsjgDao gsjgDao) {
//        this.gsjgDao = gsjgDao;
//    }

    //生成补充采购单
    @Transactional
    public void saveBccgd(Cgd ycgd) throws Exception {
        //通过原采购单拷贝补充采购单，更新采购单明细
        Cgd bccgd = new Cgd();
        ReflectionUtils.getInstance(bccgd, ycgd);
        bccgd.setCgfyList(null);
        bccgd.setYsgjList(null);

        Date now = new Date();
        List<Cgdmx> bccgdmxs = new ArrayList<Cgdmx>();
        //判断是否全部入库
        boolean flag = false;
        for (Cgdmx cgdmx : bccgd.getCgdmxList()) {
            if (cgdmx.getRksl() >= cgdmx.getSbsl()) continue;
            flag = true;
            Cgdmx bccgdmx = new Cgdmx();
            bccgdmx.setDateCreated(now);
            bccgdmx.setLastUpdated(now);
            bccgdmx.setBhsj(cgdmx.getBhsj());
            bccgdmx.setHsj(cgdmx.getHsj());
            bccgdmx.setSbsl(cgdmx.getSbsl() - cgdmx.getRksl());
            bccgdmx.setCreateUser(cgdmx.getCreateUser());
            bccgdmx.setCgd(bccgd);
            bccgdmx.setGg(cgdmx.getGg());
            bccgdmx.setJzfs(cgdmx.getJzfs());
            bccgdmx.setCd(cgdmx.getCd());
            bccgdmx.setCreateOrgan(cgdmx.getCreateOrgan());
            bccgdmx.setCreateDepartment(cgdmx.getCreateDepartment());
            bccgdmxs.add(bccgdmx);
        }

        if (!flag) {
            throw new Exception("此入库单明细已全部到货，无需生成补充采购单!");
        }

        bccgd.setId(null);
        bccgd.setDateCreated(now);
        bccgd.setLastUpdated(now);
        bccgd.setCreateUser(ycgd.getCreateUser());
        bccgd.setCreateOrgan(ycgd.getCreateOrgan());
        bccgd.setCreateDepartment(ycgd.getCreateDepartment());
        bccgd.setCgdh(this.bmService.getCgdbm(bccgd.getCglx()));
        bccgd.setZt("ytj");
        bccgd.setRksj(null);
        bccgd.setRkr(null);
        bccgd.setSfys(false);
        bccgd.setYsr(null);
        bccgd.setYsrq(null);
        bccgd.setYrk(false);
        bccgd.setYsh(false);
        bccgd.setYjs(false);
        bccgd.setBz("此为补充采购单，为：" + ycgd.getCgdh() + "生成");

        bccgd.setCgdmxList(bccgdmxs);
        cgdDao.save(bccgd);
        //原采购单更新相关信息
        ycgd.setBccgd(bccgd);
        String bz = "";
        if (ycgd.getBz() != null) {
            bz = ycgd.getBz() + ";已生成补充采购单，采购单编码为" + bccgd.getCgdh();
        } else {
            bz = "已生成补充采购单，采购单编码为" + bccgd.getCgdh();
        }
        ycgd.setBz(bz);
        cgdDao.save(ycgd);
        bgshd_wg(bccgd);
    }


    /**
     * 生成采购入库的接口参数
     *
     * @param cgd
     * @return
     */
    public String createCgdRk(Cgd cgd) {
        StringBuffer sb = new StringBuffer();
        sb.append("{\"purchaseOrderNo\":\"").append(cgd.getCgdh()).append("\",");
        sb.append("\"buyerCompany\":\"").append(cgd.getCggs().getBm()).append("\",\"items\":[");
        for (Cgdmx cgdmx : cgd.getCgdmxList()) {
            sb.append("{\"warehouseCode\":\"").append(cgd.getDzck().getBh()).append("\",");
            sb.append("\"warehouseName\":\"").append(cgd.getDzck().getMc()).append("\",");

            sb.append("\"productCode\":\"").append(cgdmx.getGg().getPmCode()).append("\",");
            sb.append("\"productName\":\"").append(cgdmx.getGg().getName()).append("\",");
            sb.append("\"specCode\":\"").append(cgdmx.getGg().getGgCode()).append("\",");
            sb.append("\"specName\":\"").append(cgdmx.getGg().getGgxh()).append("\",");
            sb.append("\"materialCode\":\"").append(cgdmx.getGg().getCzCode()).append("\",");
            sb.append("\"materialName\":\"").append(cgdmx.getGg().getCz()).append("\",");
            sb.append("\"orginCode\":\"").append(cgdmx.getCd().getBm()).append("\",");
            sb.append("\"orginName\":\"").append(cgdmx.getCd().getZ()).append("\",");
            sb.append("\"numberUnit\":\"件\",");
            sb.append("\"number\":\"").append(cgdmx.getJs() == null ? 1 : cgdmx.getJs()).append("\",");
            sb.append("\"weightUnit\":\"吨\",");
            sb.append("\"weight\":\"").append(cgdmx.getSbsl()).append("\"},");
        }
        sb = sb.delete(sb.length() - 1, sb.length());
        sb.append("]}");
        return sb.toString();
    }

    public String createStockArgs(Cgd cgd, List<Cgdmx> cgdmxList) {
        StringBuffer sb = new StringBuffer();
        sb.append("{\"purchaseOrderNo\":\"").append(cgd.getCgdh()).append("\",\"items\":[");
        for (Cgdmx cgdmx : cgdmxList) {
            Bgjhmx bgjhmx = bgjhmxDao.get(cgdmx.getKh().getBgjhmx().getId());
            Bgjh bgjh = bgjhDao.get(bgjhmx.getBgjh().getId());
            Gg gg = ggDao.get(cgdmx.getGg().getId());
            Sjzdz cd = this.sjzdzService.findSjzdzDetail(cgdmx.getCd().getId());
            sb.append("{\"buyerCompany\":\"").append(cgd.getCggs().getBm()).append("\",");
            sb.append("\"reportCompany\":\"").append(bgjh.getJhdw().getBm()).append("\",");
            sb.append("\"warehouseCode\":\"").append(cgd.getDzck().getBh()).append("\",");
            sb.append("\"productCode\":\"").append(gg.getPmCode()).append("\",");
            sb.append("\"productName\":\"").append(gg.getName()).append("\",");
            sb.append("\"specCode\":\"").append(gg.getGgCode()).append("\",");
            sb.append("\"specName\":\"").append(gg.getGgxh()).append("\",");
            sb.append("\"materialCode\":\"").append(gg.getCzCode()).append("\",");
            sb.append("\"materialName\":\"").append(gg.getCz()).append("\",");
            sb.append("\"orginCode\":\"").append(cd.getBm()).append("\",");
            sb.append("\"orginName\":\"").append(cd.getZ()).append("\",");
            sb.append("\"numberUnit\":\"件\",");
            sb.append("\"number\":\"").append(cgdmx.getRkjs() == null ? 1 : cgdmx.getRkjs()).append("\",");
            sb.append("\"weightUnit\":\"吨\",");
            sb.append("\"weight\":\"").append(cgdmx.getRksl()).append("\"},");
        }
        //根据库中采购明细生成多余货权的json
//        List<Cgdmx> cgdmxListTemp = cgd.getCgdmxList();
//        for (Cgdmx ycgdmx : cgdmxListTemp) {
//            List<Map> maps = this.countRkmxFromCgdmx(ycgdmx.getId(), cgdmxList);
//            Integer sumRkjs = (Integer) maps.get(0).get("sumRkjs");
//            Double sumRksl = (Double) maps.get(1).get("sumRksl");
//            if (ycgdmx.getSssl() > sumRksl) {
//                sb.append(createJsonToEerss(cgd, ycgdmx, sumRkjs, sumRksl));
//            }
//        }
        sb = sb.delete(sb.length() - 1, sb.length());
        sb.append("]}");
        return sb.toString();
    }

    /**
     * 生成多余货权的拼成的json
     *
     * @param cgd
     * @return
     */
    public String createJsonToEerss(Cgd cgd, Cgdmx cgdmx, int sumRkjs, Double sumRksl) {
        StringBuffer sb = new StringBuffer();
        sb.append("{\"buyerCompany\":\"").append("").append("\",");
        sb.append("\"reportCompany\":\"").append(cgd.getSbgs().getBm()).append("\",");
        sb.append("\"warehouseCode\":\"").append(cgd.getDzck().getBh()).append("\",");
        sb.append("\"productCode\":\"").append(cgdmx.getGg().getPmCode()).append("\",");
        sb.append("\"productName\":\"").append(cgdmx.getGg().getName()).append("\",");
        sb.append("\"specCode\":\"").append(cgdmx.getGg().getGgCode()).append("\",");
        sb.append("\"specName\":\"").append(cgdmx.getGg().getGgxh()).append("\",");
        sb.append("\"materialCode\":\"").append(cgdmx.getGg().getCzCode()).append("\",");
        sb.append("\"materialName\":\"").append(cgdmx.getGg().getCz()).append("\",");
        sb.append("\"orginCode\":\"").append(cgdmx.getCd().getBm()).append("\",");
        sb.append("\"orginName\":\"").append(cgdmx.getCd().getZ()).append("\",");
        sb.append("\"numberUnit\":\"件\",");
        Integer js = cgdmx.getSsjs() - sumRkjs;
        Double sl = cgdmx.getSssl() - sumRksl;
        sb.append("\"number\":\"").append(js == null ? 1 : js).append("\",");
        sb.append("\"weightUnit\":\"吨\",");
        sb.append("\"weight\":\"").append(sl).append("\"},");
        return sb.toString();
    }
}
